package Accessors;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import utils.RESTfulConnect;
import utils.URLTools;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import Callbacks.AbstractCallback;
import Enums.RFAT;
import Models.PSOFullfillment;
import Models.PendingSalesOrder;
import Presenter.PSOFullfillmentPresenter;
import Presenter.PendingSOPresenter;

@SuppressWarnings("rawtypes")
public class PendingSOAccessor extends AbstractAccessor<PendingSalesOrder,PendingSOPresenter,AbstractCallback> {
	private final String NAME = "pendingso";
	private final String DIALOG = "Pending SO";
	
	private final static PendingSOPresenter presenter = new PendingSOPresenter();
	private AbstractCallback callback = null;
	
	//Modal dialog variable.
	ProgressDialog modalDialog = null;
	
	public PendingSOAccessor(AbstractCallback callback){
		super(presenter, callback);
		this.callback = callback;
	}
	
	//Public access functions.
	public void getAllItems(final Context context){
		String dialog = "Loading " + DIALOG + " List...";
		String rfString = NAME;
		super.getAllItems(context, dialog, rfString);
	}
	
	public void getAllOpenPSOs(final Context context){
		String dialog = "Loading " + DIALOG + " List...";
		String rfString = NAME + "/runNamedQuery/PendingSO.findOpenPSOs";
		super.getAllItems(context, dialog, rfString);
	}
	
	public void getItem(final int id, final Context context){
		String dialog = "Loading " + DIALOG + "...";
		String rfString = NAME + "/" + Integer.toString(id);
		super.getItem(context, dialog, rfString);
	}
	
	public void doItemUpdate(final PendingSalesOrder item, final Context context){
		String dialog = "Updating " + DIALOG + "...";
		String rfString = NAME;
		super.doItemUpdate(item, context, dialog, rfString);
	}
	
	public void doItemInsert(final PendingSalesOrder item, final Context context){
		String dialog = "Inserting " + DIALOG + "...";
		String rfString = NAME;
		super.doItemInsert(item, context, dialog, rfString);
	}

	/*******************************************************************************
	 * Specialty Code to handle pending sales order fullfillment.
	 ******************************************************************************/
	public void doPartialFullfillment(final PendingSalesOrder item, final Context context){
		modalDialog = ProgressDialog.show(context, null, "Processing Partial Fullfillment...");
		final String strStart = URLTools.getURLString(context);
		final String str = NAME + "/fullfillPartial";
		new FullfillmentTask().execute(strStart+str, URLTools.getUSERString(context), URLTools.getPASSString(context), presenter.createJSON(item).toString());
	}
	
	private class FullfillmentTask extends AsyncTask<String, Void, String> {
    	@Override
        protected String doInBackground(String... urls) {
            try {
                return RESTfulConnect.putResource(urls[0], urls[1], urls[2], urls[3]);
            } catch (IOException e) {
            	e.printStackTrace();
            	return "Connection Error";
            }
        }
    	@SuppressWarnings("unchecked")
		@Override
        protected void onPostExecute(String result) {
    		try{
	    		modalDialog.dismiss();
	    		PSOFullfillmentPresenter psopresenter = new PSOFullfillmentPresenter();
	    		ArrayList<PSOFullfillment> items = new ArrayList<PSOFullfillment>();
	    		if(result.subSequence(0, 2).equals("<?")){
	    			PSOFullfillment item = psopresenter.tryJSONParse(result);
		    		callback.callback(item, RFAT.PSOFULLFILL_COMPLETE, items);
	    		} else {
	    			JSONObject json = new JSONObject(result);
	    			PSOFullfillment item = psopresenter.createItemFromJSONObject(json);
		    		callback.callback(item, RFAT.PSOFULLFILL_COMPLETE, items);
	    		}
    		} catch(JSONException ex){
    			ex.printStackTrace();
    		} 
        }
    }

	public void doWholeFullfillment(final PendingSalesOrder item, final Context context){
		modalDialog = ProgressDialog.show(context, null, "Processing Complete Fullfillment...");
		final String strStart = URLTools.getURLString(context);
		final String str = NAME + "/fullfillWhole";
		new FullfillmentTask().execute(strStart+str, URLTools.getUSERString(context), URLTools.getPASSString(context), presenter.createJSON(item).toString());
	}
}
